/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/

const tui = {
	//接口地址
	interfaceUrl: function() {
		// #ifdef H5
		return ''
		// #endif
		// #ifdef APP-PLUS
		return 'https://rebatemall.yuntaiqikeji.com'
		// #endif
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	//判断浏览器是否是微信浏览器
	checkIsWechatBrowser:function(){
	  return (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) =="micromessenger" );
	},
	//微信浏览器中打开H5隐藏顶部导航方法
	hidePageNavInWechatBrowser:function (){
	  //#ifdef H5
	  if (tui.checkIsWechatBrowser()) {
	    let pageNav = document.getElementsByTagName("uni-page-head");
	    if (pageNav && pageNav[0]) {
	      pageNav[0].style.display = "none";
	    }
	  }
	  //#endif
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		// 加载
		// if (!hideLoading) {
		// 	tui.delayed = setTimeout(() => {
		// 		uni.showLoading({
		// 			mask: true,
		// 			title: '请稍候...',
		// 			success(res) {
		// 				loadding = true
		// 			}
		// 		})
		// 	}, isDelay ? 1000 : 0)
		// }
		// postData['token'] = tui.getToken();
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					'content-type': isForm ? 'application/x-www-form-urlencoded' : 'application/json',
					'token': tui.getToken()
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading(); 
					}
					if (res.data && res.data.code == 400) {
						// uni.clearStorageSync();
						uni.removeStorageSync('token');
						uni.removeStorageSync('user_id');
						uni.removeStorageSync('identity');
						tui.modal('提示','登录信息已失效，请重新登录', false, () => {
							// app端进入方式
							// #ifdef  APP-PLUS
							uni.navigateTo({
								url:"/pages/login/zhanghmmdl"
							})
							// #endif
							// 小程序端进入方式
							// #ifdef MP-WEIXIN
							uni.navigateTo({
								url: "/pages/login/zhanghmmdl"
							})
							// #endif
						})
						return false;
					}
					
					if (res.data && res.data.code == 401) {
						// uni.clearStorageSync();
						uni.removeStorageSync('token');
						uni.removeStorageSync('user_id');
						uni.removeStorageSync('identity');
						tui.modal('提示',res.data.msg, false, () => {
							// uni.navigateTo({
							// 	url: '/pages/authorize/authorize'
							// })
						})
						return false;
					}
					resolve(res.data)
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'token': tui.getToken()
				},
				formData: {
					// sizeArrayText:""
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					if (d.code == 1) {
						//返回图片地址
						let fileObj = d.data;
						resolve(fileObj)
					} else {
						tui.toast(res.msg);
					}
				},
				fail: function(res) {
					console.log(res,777777)
					reject(res)
					tui.toast(res.msg);
				}
			})
		})
	},
	//获取token
	getToken() {
		return uni.getStorageSync("token");
	},
	getUserinfo: function() {
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			uni.getProvider({
				service: 'oauth',
				success: function(res) {
					if (~res.provider.indexOf('weixin')) {
						uni.login({
							provider: 'weixin',
							success: (res2) => {

								uni.getUserInfo({
									provider: 'weixin',
									success: (info) => { //这里请求接口
										info['code'] = res2['code'];
										resolve(info);

									},
									fail: () => {
										that.toast('微信登录授权失败');
									}
								})

							},
							fail: () => {
								that.toast('微信登录授权失败');
							}
						})

					} else {
						that.toast('请先安装微信或升级版本');
					}
				}
			});
			//#endif
		})

	},
	checkIsLogin() {
		// 如果token或者user_id任何一项为空就返回false
		return uni.getStorageSync("token") !== '' && uni.getStorageSync("user_id") !== '';
	},
	doLogin: function() {
		tui.modal('登录提示', '去登陆', true, function(ret) {
			if (ret) {
				// app端进入方式
				// #ifdef  APP-PLUS || H5 ||  MP-WEIXIN
				uni.navigateTo({
					url:"/pages/login/zhanghmmdl"
				})
				// #endif
				// // 小程序端进入方式
				// // #ifdef MP-WEIXIN
				// uni.navigateTo({
				// 	url: "/pages/wxAuthorization/wxAuthorization"
				// })
				// // #endif
			}
		
		});
		

	},
	saveHttpImg(url) {
		uni.showLoading({
			title: '保存中...'
		})
		uni.downloadFile({
			url: url, //仅为示例，并非真实的资源
			success: (res) => {
				if (res.statusCode === 200) {
					let file = res.tempFilePath;
					tui.save(file)
				} else {
					uni.hideLoading();
					tui.toast('保存失败');
				}
			}
		});
	},
	save(url) {
		let _this = this;
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success: () => {
				uni.hideLoading();
				tui.toast('图片已保存');
			},
			fail: () => {
				uni.hideLoading();
				tui.toast('保存失败');
			},
			complete: () => {

			}
		});
	},
	chooseImage(num,type){
		return new Promise((resolve, reject) => {
			uni.chooseImage({
			    count: num, 
			    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			    sourceType: type, //从相册选择
			    success: function (res) {
					resolve(res.tempFilePaths);
			    }
			});
		})
		
	},
	/**
	 * @param {Object} user_type  使用端，1：小程序端，2：app端，3：pc端
	 * @param {Object} payment_type 支付类型，1：微信支付，2：支付宝支付，3：余额支付（直接支付逻辑）
	 * @param {Object} order_type #订单类型，1：普通商城 2 充值 3 押金
	 * @param {Object} order_id #订单id
	 */
	getPayInfo(user_type,payment_type,order_type,order_id){
		
		return new Promise((resolve, reject) => {
			tui.request('api/pay/getPayInfo','POST',{
				user_type:user_type,
				payment_type:payment_type,
				order_type:order_type,
				order_id:order_id,
			}).then(res=>{
				resolve(res);
			}).catch(err=>{
				reject(err);
			});
		})
		
	},  
	wechatAppPay(params) {
		return new Promise((resolve, reject) => {
			// params = JSON.parse(params);
			uni.requestPayment({
				"provider": "wxpay",
				"orderInfo": {
					"appid": params.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
					"noncestr": params.noncestr, // 随机字符串
					"package": params.package, // 固定值
					"partnerid": params.partnerid, // 微信支付商户号
					"prepayid": params.prepayid, // 统一下单订单号 
					"timestamp": params.timestamp, // 时间戳（单位：秒）
					"sign": params.sign // 签名，这里用的 MD5 签名
				},
				success(res) {
					resolve(res);
				},
				fail(err) {
					console.log(err,11111111)
					resolve(err);
				}
			})
		})
	},
	wechatPay(params){
		return new Promise((resolve, reject) => {
			uni.requestPayment({
			    provider: 'wxpay',
			    timeStamp: params.timeStamp,
			    nonceStr: params.nonceStr,
			    package: params.package,
			    signType: params.signType,
			    paySign: params.paySign,
			    success: function (res) {
			        resolve(res);
			    },
			    fail: function (err) {
			        resolve(err);
			    } 
			});
		})
		
	},
	appLogin: function(platform, callback) {
		uni.getProvider({
			service: 'oauth',
			success: function(res) {
				//支持微信、qq和微博等
				if (platform == 'wxopen') {
					if (~res.provider.indexOf('weixin')) {
						uni.login({
							provider: 'weixin',
							onlyAuthorize:true,
							success: function(loginRes) {
								// console.log(loginRes);return false;
								callback({
									status: true,
									data: loginRes.code
								});
								// 获取用户信息
							// 	uni.getUserInfo({
							// 		provider: 'weixin',
							// 		success: function(infoRes) {
							// 			callback({
							// 				status: true,
							// 				data: infoRes.userInfo
							// 			});
							// 		},
							// 		fail() {
							// 			callback({
							// 				status: false,
							// 				data: {}
							// 			});
							// 		}
							// 	// });
							}
						});
					}
				}
				if (platform == 'qq') {
					//支持微信、qq和微博等
					if (~res.provider.indexOf('qq')) {
						uni.login({
							provider: 'qq',
							success: function(loginRes) {
								// 获取用户信息
								uni.getUserInfo({
									provider: 'qq',
									success: function(infoRes) {
										callback({
											status: true,
											data: infoRes.userInfo
										});
									},
									fail() {
										callback({
											status: false,
											data: {}
										});
									}
								});
							}
						});
					}
				}
			},
			fail() {
				callback({
					status: false,
					data: {}
				});
			}
		});
	},
	// 小程序保存图片
	    savePosterPath(url) {
	      uni.downloadFile({
	        url:url,
	        success: (resFile) => {
	          if (resFile.statusCode === 200) {
	            uni.getSetting({ 
	              success: (res) => {
					
	                if (!res.authSetting["scope.writePhotosAlbum"]) {
						
	                  uni.authorize({
	                    scope: "scope.writePhotosAlbum",
	                    success: () => {
	                      uni.saveImageToPhotosAlbum({
	                        filePath: resFile.tempFilePath,
	                        success: (res) => {
	                         uni.showToast({
	                            title: "保存成功！",
	                          }); 
	                        },
	                        fail: (res) => {
	                          uni.showToast({
	                            title: res.errMsg,
	                          });
	                        },
	                        complete: (res) => {},
	                      });
	                    },
	                    fail: () => {
	                      uni.showModal({
	                        title: "您已拒绝获取相册权限",
	                        content: "是否进入权限管理，调整授权？",
	                        success: (res) => {
	                          if (res.confirm) {
	                            uni.openSetting({
	                              success: (res) => {
	                              },
	                            });
	                          } else if (res.cancel) {
	                            uni.showToast({
	                              title: "已取消！",
	                            });
	                          }
	                        },
	                      });
	                    },
	                  });
	                } else {
	                  uni.saveImageToPhotosAlbum({
	                    filePath: resFile.tempFilePath,
	                    success: (res) => {
	                      uni.showToast({ 
	                        title: "保存成功！",
	                      });
	                    },
	                    fail: (res) => {
	                      uni.showToast({
	                        title: '取消保存',
	                      });
	                    },
	                    complete: (res) => {},
	                  });
	                }
	              },
	              fail: (res) => {
					  
					  
				  },
	            });
	          } else {
	            uni.showToast({
	              title: resFile.errMsg,
	            });
	          }
	        },
	        fail: (res) => {
				
	          uni.showToast({
	            title: res.errMsg,
	          });
	        },
	      });
	    },
		
		 /**
		   * scene解码
		   */
		  scene_decode(e) {
		    if (e === undefined)
		      return {};
		    let scene = decodeURIComponent(e),
		      params = scene.split(','),
		      data = {};
		    for (let i in params) {
		      var val = params[i].split(':');
		      val.length > 0 && val[0] && (data[val[0]] = val[1] || null)
		    }
		    return data;
		  },
		  
		     /**
		     * 获取场景值(scene)
		     */
		    getSceneData(query) {
		      return query.scene ? tui.scene_decode(query.scene) : {};
		    },
			


} 

export default tui
module.exports = {
	getUserinfo: tui.getUserinfo,
	request: tui.request,
	toast: tui.toast,
	checkIsLogin: tui.checkIsLogin,
	doLogin: tui.doLogin,
	saveHttpImg: tui.saveHttpImg,
	chooseImage:tui.chooseImage,
	uploadFile:tui.uploadFile,
	getPayInfo:tui.getPayInfo,
	wechatPay:tui.wechatPay,
	modal:tui.modal,
	appLogin: tui.appLogin,
	wechatAppPay: tui.wechatAppPay,
	savePosterPath:tui.savePosterPath,
	getSceneData:tui.getSceneData,
	hidePageNavInWechatBrowser:tui.hidePageNavInWechatBrowser
};
